package com.lagou.task.utils;


import java.sql.*;

/**
 * 数据库工具类
 */
public class Dbutils {
    // 1.定义常量，保存数据库相关连接信息
    private static String jdbcName;
    private static String dbUrl;
    private static String dbUserName;
    private static String dbPassword;

    // 2.编写静态代码块，数据库配置
    static {
        jdbcName = "com.mysql.jdbc.Driver";
        dbUrl = "jdbc:mysql://localhost:3306/studentSystem?characterEncoding=UTF-8";
        dbUserName = "root";
        dbPassword = "7458";
        try {
            Class.forName(jdbcName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
        return connection;
    }

    /**
     * 增删改关闭连接
     * @param connection
     * @param statement
     */
    public static void close(Connection connection, Statement statement){
        if (connection != null && statement != null){
            try {
                statement.close();
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 查询关闭连接
     * @param connection
     * @param statement
     * @param resultSet
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (connection != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
